package com.lagou.lesson2.factory;

import com.lagou.lesson2.core.annotation.Transactional;

import java.lang.reflect.Method;

public class AnnotationAspectJAutoProxyCreator<T> {
    private static AnnotationAspectJAutoProxyCreator instance = new AnnotationAspectJAutoProxyCreator();
    private AnnotationAspectJAutoProxyCreator() {

    }
    public static AnnotationAspectJAutoProxyCreator getInstance() {
        return instance;
    }

    /**
     * 根据注解配置，自动创建代理对象
     * @param obj
     * @return
     */
    public T processAnnotationAspectProxy(T obj) {
        Class<?>[] interfaces = obj.getClass().getInterfaces();
        // 如果实现了接口，使用JDK动态代理
        if (interfaces != null && interfaces.length > 0) {
            return (T) AnnotationTransactionProxyFactory.getInstance().getJdkProxy(obj);
        }
        // 否则使用Cglib生成代理对象
        return (T) AnnotationTransactionProxyFactory.getInstance().getCglibProxy(obj);
    }


    /**
     * 判断是否是事务注解
     * @param aClass
     * @return
     */
    private boolean isTransactional(Class<?> aClass){
        Transactional classTransactionAnnotation = aClass.getAnnotation(Transactional.class);
        if(classTransactionAnnotation!=null){
            return true;
        }else{
            Method[] declaredMethods = aClass.getDeclaredMethods();
            if(declaredMethods!=null){
                for (Method declaredMethod : declaredMethods) {
                    if(declaredMethod.getAnnotation(Transactional.class)!=null){
                        return true;
                    }
                }
            }

        }
        return false;
    }
}
